package hn.cch.servlet.controller;

import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.context.request.async.DeferredResult;

import java.util.concurrent.Callable;
import java.util.concurrent.LinkedBlockingQueue;
import java.util.concurrent.ThreadPoolExecutor;
import java.util.concurrent.TimeUnit;

@RequestMapping(value = "/async")
public class AsyncController {

    private static final Logger logger = LoggerFactory.getLogger(AsyncController.class);

    private static final ThreadPoolExecutor executor = new ThreadPoolExecutor(2, 4, 30, TimeUnit.SECONDS, new LinkedBlockingQueue<>(5));


    @GetMapping(value = "/getDeferredResult")
    public DeferredResult<String> getDeferredResult() {
        DeferredResult<String> deferredResult = new DeferredResult<>();
        executor.execute(() -> {
            try {
                Thread.sleep(1000);
                deferredResult.setResult("result");
            } catch (Exception e) {
                logger.error("error:", e);
                deferredResult.setErrorResult("error");
            }

        });

        return deferredResult;
    }

    @GetMapping(value = "/getCallable")
    public Callable<String> getCallable() {
        // SimpleAsyncTaskExecutor
        return () -> {
            try {
                Thread.sleep(1000);
                return "result";
            } catch (Exception e) {
                logger.error("error:", e);
                return "error";
            }
        };
    }

}
